import { FC, ReactNode, useState, useLayoutEffect } from 'react';
import { createPortal } from '@tarojs/react';
import { useRouter } from '@tarojs/taro';
import './index.scss';

const SysPortal: FC<{
  children?: ReactNode;
  enable?: boolean;
}> = (props) => {
  const {
    children,
    enable,
  } = props;
  const [dom, setDom] = useState<HTMLElement | null>(null);
  const router = useRouter();
  useLayoutEffect(() => {
    const _dom = document.getElementById(router?.['$taroPath']);
    _dom && setDom(_dom);
  }, [router?.['$taroPath']]);
  return ((enable && dom)
    ? createPortal(children, dom)
    : children);
};

SysPortal.defaultProps = {
  enable: !1,
};

export default SysPortal;
